package com.xzh.homeliving.commodity.exception;

import com.xzh.common.domain.enums.HttpStatusEnum;
import com.xzh.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;

/**
 * @Author: zhiHong
 * @CreateTime: 2024-01-27 0:00
 * @Description: 统一异常处理类,其中ControllerAdvice用来统一接管指定包下的异常
 */
@Slf4j
@ResponseBody
@ControllerAdvice(basePackages = "com.xzh.homeliving.commodity.controller")
public class ExceptionControllerAdvice {
    // 如果包下抛出了数据校验异常，就交由 handlerValidException 处理
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public R handleValidException(MethodArgumentNotValidException e) {
        //log.error("数据校验出现问题{}， 异常类型是{}", e.getMessage(), e.getClass());
        //得到BindingResult
        BindingResult bindingResult = e.getBindingResult();
        HashMap<String, String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return R.error(HttpStatusEnum.INVALID_EXCEPTION.getCode(), "方法参数异常").put("data", errorMap);
    }

    @ExceptionHandler({Throwable.class})
    public R handleException(Throwable throwable) {
        return R.error(HttpStatusEnum.UNKNOWN_EXCEPTION.getCode(), "系统未知错误");
    }
}
